package com.xq.tmall.controller.fore;

import com.alibaba.fastjson.JSONObject;
import com.xq.tmall.controller.BaseController;
import com.xq.tmall.entity.*;
import com.xq.tmall.service.*;
import com.xq.tmall.util.PageUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 地址管理
 */
@Controller
public class ForeMyAddressController extends BaseController {
    @Resource(name = "detailaddressService")
    private DetailaddressService detailaddressService;
    @Resource(name = "userService")
    private UserService userService;
    @Resource(name = "productOrderItemService")
    private ProductOrderItemService productOrderItemService;
    @Resource(name = "addressService")
    private AddressService addressService;
    @Resource(name = "categoryService")
    private CategoryService categoryService;
    @Resource(name = "productImageService")
    private ProductImageService productImageService;
    @Resource(name = "productService")
    private ProductService productService;
    //转到前台天猫-用户地址建立页
    @RequestMapping(value = "address/create/{id}/{order_item_list}", method = RequestMethod.GET)
    public String goToOrderConfirmPage(@PathVariable("id") Integer id, Map<String, Object> map, HttpSession session, HttpServletRequest request, @PathVariable("order_item_list") String order_item_list) throws UnsupportedEncodingException {
        logger.info("检查用户是否登录");
        Object userId = checkUser(session);
        User user;
        if (userId != null) {
            logger.info("获取用户信息");
            user = userService.get(Integer.parseInt(userId.toString()));
            map.put("user", user);
        } else {
            return "redirect:/login";
        }

        Detailaddress detailaddress = detailaddressService.queryById(id);
        logger.info("通过地址UserID获取地址列表信息：{}", detailaddress.getUserId());
        Map<String,String> stringMap=addressService.getByAddress(detailaddress.getAddressId().toString());


        //初始化订单地址信息
        String addressId = stringMap.get("proId");
        String cityAddressId = stringMap.get("cityId");
        String districtAddressId = stringMap.get("countryId");
        String detailsAddress = detailaddress.getDetailAddress();
        String order_post = detailaddress.getPost();
        String order_receiver = detailaddress.getReceiver();
        String order_phone = detailaddress.getPhone();

        logger.info("获取省份信息");
        List<Address> addressList = addressService.getRoot();
        logger.info("获取addressId为{}的市级地址信息", addressId);
        List<Address> cityAddress = addressService.getList(null, addressId);
        logger.info("获取cityAddressId为{}的区级地址信息", cityAddressId);
        List<Address> districtAddress = addressService.getList(null, cityAddressId);
        extracted(map, addressId, cityAddressId, districtAddressId, detailsAddress, order_post, order_receiver, order_phone, addressList, cityAddress, districtAddress);
        String[] split = order_item_list.split(",");
        Integer[] integers=new Integer[split.length];
        for (int i = 0; i < split.length; i++) {
            integers[i]=Integer.valueOf(split[i]);
        }
        List<ProductOrderItem> orderItemList = new ArrayList<>(integers.length);
       for (Integer orderItem_id : integers) {
            orderItemList.add(productOrderItemService.get(orderItem_id));
        }
        double orderTotalPrice = 0.0;
        for (ProductOrderItem orderItem : orderItemList) {

            Product product = productService.get(orderItem.getProductOrderItem_product().getProduct_id());
            product.setProduct_category(categoryService.get(product.getProduct_category().getCategory_id()));
            product.setSingleProductImageList(productImageService.getList(product.getProduct_id(), (byte) 0, new PageUtil(0, 1)));
            orderItem.setProductOrderItem_product(product);
            orderTotalPrice += orderItem.getProductOrderItem_price();
        }
        map.put("orderItemList", orderItemList);
        map.put("orderTotalPrice", orderTotalPrice);

        logger.info("转到前台天猫-订单建立页");
        return "fore/productBuyPage";
    }




    //顶部导航栏跳到地址管理
    @RequestMapping(value = "address/create/{id}", method = RequestMethod.GET)
    public String goToOrderConfirmPage(@PathVariable("id") Integer id, Map<String, Object> map, HttpSession session, HttpServletRequest request) throws UnsupportedEncodingException {
        logger.info("检查用户是否登录");
        Object userId = checkUser(session);
        User user;
        if (userId != null) {
            logger.info("获取用户信息");
            user = userService.get(Integer.parseInt(userId.toString()));
            map.put("user", user);
        } else {
            return "redirect:/login";
        }

        Detailaddress detailaddress = detailaddressService.queryById(id);
        logger.info("通过地址UserID获取地址列表信息：{}", detailaddress.getUserId());
        Map<String,String> stringMap=addressService.getByAddress(detailaddress.getAddressId().toString());


        //初始化订单地址信息
        String addressId = stringMap.get("proId");
        String cityAddressId = stringMap.get("cityId");
        String districtAddressId = stringMap.get("countryId");
        String detailsAddress = detailaddress.getDetailAddress();
        String order_post = detailaddress.getPost();
        String order_receiver = detailaddress.getReceiver();
        String order_phone = detailaddress.getPhone();

        logger.info("获取省份信息");
        List<Address> addressList = addressService.getRoot();
        logger.info("获取addressId为{}的市级地址信息", addressId);
        List<Address> cityAddress = addressService.getList(null, addressId);
        logger.info("获取cityAddressId为{}的区级地址信息", cityAddressId);
        List<Address> districtAddress = addressService.getList(null, cityAddressId);
        extracted(map, addressId, cityAddressId, districtAddressId, detailsAddress, order_post, order_receiver, order_phone, addressList, cityAddress, districtAddress);
        logger.info("转到前台天猫-订单建立页");
        return "fore/productBuyPage";
    }


    private List<ProductOrderItem> getProductOrderItems(@RequestParam(required = false) Integer[] order_item_list) {
        return new ArrayList<>(order_item_list.length);
    }

    //转到前台天猫-用户地址建立页
    @RequestMapping(value = "address/create/{id}/{pid}/{pNum}", method = RequestMethod.GET)
    public String goToOrderConfirmPage(@PathVariable("id") Integer id, Map<String, Object> map, HttpSession session,HttpServletRequest request,
                                       @PathVariable("pid") String pid,@PathVariable("pNum") String pNum
    ) throws UnsupportedEncodingException {
        logger.info("检查用户是否登录");
        Object userId = checkUser(session);
        User user;
        if (userId != null) {
            logger.info("获取用户信息");
            user = userService.get(Integer.parseInt(userId.toString()));
            map.put("user", user);
        } else {
            return "redirect:/login";
        }

        Detailaddress detailaddress = detailaddressService.queryById(id);
        logger.info("通过地址UserID获取地址列表信息：{}", detailaddress.getUserId());
        Map<String,String> stringMap=addressService.getByAddress(detailaddress.getAddressId().toString());


        //初始化订单地址信息
        String addressId = stringMap.get("proId");
        String cityAddressId = stringMap.get("cityId");
        String districtAddressId = stringMap.get("countryId");
        String detailsAddress = detailaddress.getDetailAddress();
        String order_post = detailaddress.getPost();
        String order_receiver = detailaddress.getReceiver();
        String order_phone = detailaddress.getPhone();

        logger.info("获取省份信息");
        List<Address> addressList = addressService.getRoot();
        logger.info("获取addressId为{}的市级地址信息", addressId);
        List<Address> cityAddress = addressService.getList(null, addressId);
        logger.info("获取cityAddressId为{}的区级地址信息", cityAddressId);
        List<Address> districtAddress = addressService.getList(null, cityAddressId);
        extracted(map, addressId, cityAddressId, districtAddressId, detailsAddress, order_post, order_receiver, order_phone, addressList, cityAddress, districtAddress);
        Product product = productService.get(Integer.valueOf(pid));
        if (product == null) {
            return "redirect:/";
        }
        logger.info("获取产品的详细信息");
        product.setProduct_category(categoryService.get(product.getProduct_category().getCategory_id()));
        product.setSingleProductImageList(productImageService.getList(Integer.parseInt(pid), (byte) 0, new PageUtil(0, 1)));

        logger.info("封装订单项对象");
        ProductOrderItem productOrderItem = new ProductOrderItem();
        productOrderItem.setProductOrderItem_product(product);
        Short aShort = Short.valueOf(pNum);
        productOrderItem.setProductOrderItem_number(aShort);
        productOrderItem.setProductOrderItem_price(product.getProduct_sale_price() * aShort);
        productOrderItem.setProductOrderItem_user(new User().setUser_id(Integer.valueOf(userId.toString())));
        map.put("orderTotalPrice", productOrderItem.getProductOrderItem_price());
        List<ProductOrderItem> productOrderItemList = new ArrayList<>();
        productOrderItemList.add(productOrderItem);
        map.put("orderItemList", productOrderItemList);

        logger.info("转到前台天猫-订单建立页");
        return "fore/productBuyPage";
    }


    @RequestMapping(value = "/detailAddress/{pid}/{pNum}", method = RequestMethod.GET)
    public String getLookRecrod(HttpSession session, Map<String,Object> map,@PathVariable("pid") Integer pid,@PathVariable("pNum") Integer pNum){
        logger.info("检查用户是否登录");
        Object userId = checkUser(session);
        if (userId != null) {
            logger.info("获取用户信息");
            User user = userService.get(Integer.parseInt(userId.toString()));
            map.put("user", user);
        }else {
            logger.info("用户未登录-跳转登录界面");
            return "redirect:/login";
        }

        logger.info("查询用户收货地址");

        //浏览记录商品信息详情列表
        List<Detailaddress> list= detailaddressService.queryListByUserId(Integer.parseInt(userId.toString()));
        map.put("totalPage", list.size());
        map.put("adressDetails", list);
        map.put("pid",pid);
        map.put("pNum",pNum);
        return "fore/addressDetail";
    }

    @RequestMapping(value = "/detailAddress/getCar/{order_item_list}", method = RequestMethod.GET)
    public String getCar(HttpSession session, Map<String,Object> map, @PathVariable("order_item_list") String order_item_list){
        logger.info("检查用户是否登录");
        Object userId = checkUser(session);
        if (userId != null) {
            logger.info("获取用户信息");
            User user = userService.get(Integer.parseInt(userId.toString()));
            map.put("user", user);
        }else {
            logger.info("用户未登录-跳转登录界面");
            return "redirect:/login";
        }
        logger.info("查询用户收货地址");
        //浏览记录商品信息详情列表
        List<Detailaddress> list= detailaddressService.queryListByUserId(Integer.parseInt(userId.toString()));
        map.put("totalPage", list.size());
        map.put("adressDetails", list);
        map.put("order_item_list",order_item_list);
        return "fore/addressDetail";
    }

    @RequestMapping(value = "/detailAddress", method = RequestMethod.GET)
    public String detailAddress(HttpSession session, Map<String,Object> map){
        logger.info("检查用户是否登录");
        Object userId = checkUser(session);
        if (userId != null) {
            logger.info("获取用户信息");
            User user = userService.get(Integer.parseInt(userId.toString()));
            map.put("user", user);
        }else {
            logger.info("用户未登录-跳转登录界面");
            return "redirect:/login";
        }
        logger.info("查询用户收货地址");
        //浏览记录商品信息详情列表
        List<Detailaddress> list= detailaddressService.queryListByUserId(Integer.parseInt(userId.toString()));
        map.put("totalPage", list.size());
        map.put("adressDetails", list);
        return "fore/addressDetail";
    }


    //转到前台天猫-订单建立页
    @RequestMapping(value = "addressList", method = RequestMethod.GET, produces = "application/json;charset=utf-8")
    public String addressList(Map<String, Object> map, HttpSession session, HttpServletRequest request) {
        logger.info("检查用户是否登录");
        Object userId = checkUser(session);
        User user;
        if (userId != null) {
            logger.info("获取用户信息");
            user = userService.get(Integer.parseInt(userId.toString()));
            map.put("user", user);
        } else {
            return "redirect:/login";
        }

        //初始化订单地址信息
        String addressId = "110000";
        String cityAddressId = "110100";
        String districtAddressId = "110101";
        String detailsAddress = null;
        logger.info("获取省份信息");
        List<Address> addressList = addressService.getRoot();
        logger.info("获取addressId为{}的市级地址信息", addressId);
        List<Address> cityAddress = addressService.getList(null, addressId);
        logger.info("获取cityAddressId为{}的区级地址信息", cityAddressId);
        List<Address> districtAddress = addressService.getList(null, cityAddressId);
        extracted(map, addressId, cityAddressId, districtAddressId, detailsAddress, null, null, null, addressList, cityAddress, districtAddress);
        logger.info("地址管理页面");
        return "fore/addressAdd";
    }

    private void extracted(Map<String, Object> map, String addressId, String cityAddressId, String districtAddressId, String detailsAddress, String order_post, String order_receiver, String order_phone, List<Address> addressList, List<Address> cityAddress, List<Address> districtAddress) {
        map.put("addressList", addressList);
        map.put("cityList", cityAddress);
        map.put("districtList", districtAddress);
        map.put("addressId", addressId);
        map.put("cityAddressId", cityAddressId);
        map.put("districtAddressId", districtAddressId);
        map.put("order_post", order_post);
        map.put("order_receiver", order_receiver);
        map.put("order_phone", order_phone);
        map.put("detailsAddress", detailsAddress);
    }



    //创建地址项-ajax
    @ResponseBody
    @RequestMapping(value = "addressDetail/add", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
    public String addAddressDetail(HttpSession session, Map<String, Object> map, HttpServletResponse response,
                                    @RequestParam Integer districtAddressId, @RequestParam String productOrder_detail_address,
                                    @RequestParam String productOrder_post, @RequestParam String productOrder_receiver,
                                    @RequestParam String productOrder_mobile)  {
        JSONObject object = new JSONObject();
        logger.info("检查用户是否登录");
        Object userId = checkUser(session);
        if (userId == null) {
            object.put("success", false);
            object.put("url", "/login");
            return object.toJSONString();
        }
        Detailaddress detailaddress = new Detailaddress()
                .setAddressId(districtAddressId).setPost(productOrder_post).setUserId(Integer.valueOf(userId.toString()))
                .setPhone(productOrder_mobile).setReceiver(productOrder_receiver).setDetailAddress(productOrder_detail_address);
        Boolean insert = detailaddressService.insert(detailaddress);
        if (!insert) {
            throw new RuntimeException();
        }
        object.put("success", true);
        object.put("url", "/detailAddress");
        return object.toJSONString();
    }

    //创建地址项-ajax
    @ResponseBody
    @RequestMapping(value = "addressDetail/delete", method = RequestMethod.GET, produces = "application/json;charset=utf-8")
    public String deleteAddressDetail(HttpSession session, Map<String, Object> map, HttpServletResponse response, @RequestParam("id") Integer id)  {
        JSONObject object = new JSONObject();
        logger.info("检查用户是否登录");
        Object userId = checkUser(session);
        if (userId == null) {
            object.put("success", false);
            object.put("url", "/login");
            return object.toJSONString();
        }
        Boolean delete = detailaddressService.deleteById(id);
        if (!delete) {
            throw new RuntimeException();
        }
        object.put("success", true);
        object.put("url", "/detailAddress");
        return object.toJSONString();
    }



}
